﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Lexalytics;
using System.IO;
using System.Threading;
using Microsoft.Win32;

namespace SalienceEngineDemo
{
    public partial class SalienceDemo : Form
    {
        public static SalienceFive oSalienceSession;
        public static Configuration oConfig;
        private bool m_bUIEnabled = false;
        private bool CategoryIsSelected = true;

        // Controls for document methods
        private ctrlGetDocumentDetails oGetDocumentDetails;
        private ctrlGetDocumentSentiment oGetDocumentSentiment;
        private ctrlGetSummary oGetSummary;
        private ctrlGetDocumentThemes oGetDocumentThemes;
        private ctrlGetDocumentQueryTopics oGetDocumentQueryTopics;
        private ctrlGetDocumentConceptTopics oGetDocumentConceptTopics;
        private ctrlGetDocumentCategoryTopics oGetDocumentCategoryTopics;

        // Controls for named and user-defined entities
        private ctrlGetEntities oGetEntities;
        private ctrlGetEntities oGetUserEntities;
        private ctrlGetRelationships oGetRelationships;
        private ctrlGetRelationships oGetUserRelationships;
        private ctrlGetOpinions oGetOpinions;
        private ctrlGetOpinions oGetUserOpinions;

        // Controls for markup functions
        private ctrlGetPOSTaggedText oGetPOSTaggedText;
        private ctrlGetEntityTaggedText oGetEntityTaggedText;
        private ctrlGetOpinionTaggedText oGetOpinionTaggedText;
        private ctrlGetSentimentTaggedText oGetSentimentTaggedText;

        // Deprecated controls
        private ctrlGetSimpleEntities oGetSimpleEntities;
        private ctrlGetEntities oGetQuotes;
        private ctrlGetDocumentChunks oGetDocumentChunks;


        #region Constants for treeview methods
        private const int TV_DOCUMENT_DETAILS = 34;
        private const int TV_DOCUMENT_SENTIMENT = 32;
        private const int TV_DOCUMENT_SUMMARY = 31;
        private const int TV_DOCUMENT_THEMES = 33;
        private const int TV_DOCUMENT_QUERY_TOPICS = 35;
        private const int TV_DOCUMENT_CONCEPT_TOPICS = 36;
        private const int TV_DOCUMENT_CATEGORIES = 37;

        private const int TV_NAMED_ENTITY_ENTITIES = 11;
        private const int TV_NAMED_ENTITY_RELATIONSHIPS = 14;
        private const int TV_NAMED_ENTITY_OPINIONS = 15;

        private const int TV_USER_ENTITY_ENTITIES = 301;
        private const int TV_USER_ENTITY_RELATIONSHIPS = 302;
        private const int TV_USER_ENTITY_OPINIONS = 303;

        private const int TV_MARKUP_POS = 21;
        private const int TV_MARKUP_NAMED_ENTITY = 22;
        private const int TV_MARKUP_SENTIMENT = 23;
        private const int TV_MARKUP_OPINION = 26;

        #endregion

        bool bAnsiMode = true;
        
        public SalienceDemo()
        {
            oConfig = new Configuration();
            TestSettings(); // Used to future-proof any crashes that may happen when dealing with old settings
            InitializeComponent(); 
            SetupOptionProfiles();
            
            //Show the splash screen
            Thread th = new Thread(new ThreadStart(this.DoSplash));
            th.Start();
            Thread.Sleep(2500);
            th.Abort();
            Thread.Sleep(1000);
            treeView1.ExpandAll();
            //Put in all the place holders for the panels, we create them if that function gets called
            this.oGetEntities = null;
            this.oGetUserEntities = null;
            this.oGetSimpleEntities = null;
            this.oGetPOSTaggedText = null;
            this.oGetEntityTaggedText = null;
            this.oGetSentimentTaggedText = null;
            this.oGetSummary = null;
            this.oGetDocumentSentiment = null;
            this.oGetDocumentThemes = null;
            this.oGetDocumentChunks = null;
            this.oGetRelationships = null;
            this.oGetUserRelationships = null;
            this.oGetOpinions = null;
            this.oGetUserOpinions = null;
            this.oGetDocumentDetails = null;
            this.oGetOpinionTaggedText = null;
            this.oGetDocumentQueryTopics = null;
            this.oGetDocumentConceptTopics = null;
            this.oGetDocumentCategoryTopics = null;
            this.currentText.Font = new Font(this.currentText.Font.FontFamily, Properties.Settings.Default.fFontSize);
        }
        
        #region Form methods

        private void TestSettings()
        {
            List<Settings> toDelete = new List<Settings>();
            for (int i = 0; i < oConfig.userSettings.Count; i++)
            {
                string testName = "";
                string testDataPath = "";
                try
                {
                    testDataPath = oConfig.userSettings[i].settings["DataDirectory"];
                }
                catch (Exception)
                {
                    File.Delete(oConfig.userSettings[i].settingsPath);
                    toDelete.Add(oConfig.userSettings[i]);
                    continue;
                }
                try
                {
                    testName = oConfig.userSettings[i].settings["Name"];
                }
                catch (Exception)
                {
                    testName = Path.GetFileNameWithoutExtension(oConfig.userSettings[i].settingsPath);
                }
                Settings TestSettings = new Settings(testName, testDataPath, oConfig.sInstallRoot, testDataPath.Contains("twitter") ? true : false);
                foreach (KeyValuePair<string, string> oPair in TestSettings.settings)
                {
                    try
                    {
                        String value = oConfig.userSettings[i].settings[oPair.Key];
                    }
                    catch (Exception)
                    {
                        oConfig.userSettings[i].settings.Add(oPair.Key, oPair.Value);
                    }
                }
                oConfig.userSettings[i].Save();
            }
            for (int i = 0; i < toDelete.Count; i++)
            {
                oConfig.userSettings.Remove(toDelete[i]);
            }
        }

            // Add Option Profiles to the Drop Down boxes
        private void SetupOptionProfiles()
        {
            List<int> toDelete = new List<int>();
            int nCustomProfiles = 0;
            for (int i = 0; i < oConfig.userSettings.Count; i++)
            {
                if (!oConfig.userSettings[i].settings.ContainsKey("Name"))
                {
                    continue;
                }
                string sDropDownTitle = String.Empty;
                bool bIsDefault = true;
                // Changes visual title for the data directory depending on language/content form
                switch (oConfig.userSettings[i].settings["Name"])
                {
                    case "twitter_data":
                        sDropDownTitle = "Short Mode (twitter_data)";
                        break;
                    case "data":
                        sDropDownTitle = "Default Mode (data)";
                        break;
                    case "zh-data":
                        sDropDownTitle = "Chinese Mode (zh-data)";
                        break;
                    case "es-data":
                        sDropDownTitle = "Spanish Mode (es-data)";
                        break;
                    case "pt-data":
                        sDropDownTitle = "Portuguese Mode (pt-data)";
                        break;
                    case "de-data":
                        sDropDownTitle = "German Mode (de-data)";
                        break;
                    case "fr-data":
                        sDropDownTitle = "French Mode (fr-data)";
                        break;
                    default:
                        bIsDefault = false;
                        nCustomProfiles++;
                        sDropDownTitle = oConfig.userSettings[i].settings["Name"];
                        break;
                }
                if (!StillExists(oConfig.userSettings[i].settings["DataDirectory"]) && bIsDefault)
                {
                    toDelete.Add(i);
                }
                else
                {
                    this.cmbModeSwitch.Items.Add(sDropDownTitle);
                }
            }
            Settings SelectedSetting = oConfig.userSettings[Properties.Settings.Default.nMode];
            for (int i = 0; i < toDelete.Count; i++)
            {
                File.Delete(oConfig.userSettings[toDelete[i]].settingsPath);
                oConfig.userSettings.RemoveAt(toDelete[i]);
            }
            for (int i = 0; i < oConfig.userSettings.Count; i++)
            {
                if (SelectedSetting == oConfig.userSettings[i])
                {
                    Properties.Settings.Default.nMode = i;
                    Properties.Settings.Default.Save();
                    break;
                }
            }
            this.cmbModeSwitch.Items.Add("<Custom Profile>");
            this.cmbModeSwitch.SelectedIndex = Properties.Settings.Default.nMode;
        }

        private bool StillExists(string sDataDir)
        {
            if (!Directory.Exists(sDataDir))
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// I have no idea why this works, but without it the form doesn't always get sent to the front after the
        /// splash screen is displayed. -Paul
        /// </summary>
        protected override void OnActivated(EventArgs e)
        {
            base.OnActivated(e);
            this.Activate();
            this.Show();
        }
        #endregion

        #region Menu item handlers
        //Load a text file into the system, saves all that tedious cutting and pasting
        private void loadFileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
            {
                try
                {
                    bAnsiMode = true;
                    Stream oStream = openFileDialog1.OpenFile();
                    StreamReader oReader = new StreamReader(oStream, Encoding.UTF8);
                    string sText = oReader.ReadToEnd();
                    if(sText.Contains("�"))
                    {
                        oStream.Position = 0;
                        oReader = new StreamReader(oStream, Encoding.Default);
                        sText = oReader.ReadToEnd();
                    }
                    currentText.Text = sText;
                    
                    oReader.Close();
                }
                catch (System.IO.IOException exception)
                {
                    MessageBox.Show(exception.Message, "Error Loading File", MessageBoxButtons.OK);
                    currentText.Text = "";
                }
            }
        }

        public void StartOptionsDialog(int View)
        {
            Dialogs.Options dlgOptions;
            if (View != (int)Dialogs.Options.OptionSections.NOTHING)
                dlgOptions = new Dialogs.Options(View, this);
            else
                dlgOptions = new Dialogs.Options(this);
            if (dlgOptions.ShowDialog() == DialogResult.OK)
            {
                bool bReady = false;
                // Reinitialize session if needed
                if (dlgOptions.bChangesRequireRestart)
                    bReady = InitializeSalienceSession(true);
                else
                    bReady = true;

                // Set additional options
                if (bReady)
                    bReady = SetSalienceOptions();

                this.currentText.Font = new Font(this.currentText.Font.FontFamily, Properties.Settings.Default.fFontSize);
                foreach (Control control in this.Controls)
                {
                    try
                    {
                        ((DemoControl)control).SetFontSize();
                        break;
                    }
                    catch (Exception) { }
                }
                EnableUI(bReady);
            }
        }

        public void optionsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (CategoryIsSelected)
                StartOptionsDialog(-1);
            else
            {
                foreach (Control control in this.Controls)
                {
                    try
                    {
                        ((DemoControl)control).btnOptions_Click(sender, e);
                        break;
                    }
                    catch (Exception) { }
                }
            }   
        }

        private void helpToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Dialogs.AboutBox dlgAbout = new Dialogs.AboutBox();
            dlgAbout.ShowDialog();
        }

        private void refreshEngineToolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.Windows.Forms.Cursor.Current = Cursors.WaitCursor;
            InitializeSalienceSession(true);
            System.Windows.Forms.Cursor.Current = Cursors.Default;
        }


        private void reinitializeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // Get default data location from install root
            string sInstallRoot = oConfig.sInstallRoot;

            folderBrowserDialog1.Description = "Select data directory for Salience session.";
            if (Directory.Exists(sInstallRoot))
            {
                folderBrowserDialog1.SelectedPath = sInstallRoot;
                if (Directory.Exists(sInstallRoot + "\\data"))
                    folderBrowserDialog1.SelectedPath = sInstallRoot + "\\data";
            }

            if (folderBrowserDialog1.ShowDialog(this) == DialogResult.OK)
            {
                SalienceDemo.oSalienceSession.Dispose();

                // Initialize a new session with selected data directory
                oSalienceSession = new SalienceFive(sInstallRoot + "\\license.v5", folderBrowserDialog1.SelectedPath);
                //Set the status strip
                toolStripStatusLabel1.Text = "Data Root: " + folderBrowserDialog1.SelectedPath;

                // Set user directory based on data directory selection, as an initial guess
                oSalienceSession.SetUserDirectory(folderBrowserDialog1.SelectedPath + "\\user");
                toolStripStatusLabel2.Text = "User Root: " + folderBrowserDialog1.SelectedPath + "\\user";

            }

            // Set the user directory
            folderBrowserDialog1.Description = "Select user directory for Salience session.";
            if (Directory.Exists(folderBrowserDialog1.SelectedPath + "\\user"))
                folderBrowserDialog1.SelectedPath = folderBrowserDialog1.SelectedPath + "\\user";

            if (folderBrowserDialog1.ShowDialog(this) == DialogResult.OK)
            {
                oSalienceSession.SetUserDirectory(folderBrowserDialog1.SelectedPath);
                toolStripStatusLabel2.Text = "User Root: " + folderBrowserDialog1.SelectedPath;
            }

        }

        private void addHSDToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (openFileDialog2.ShowDialog(this) == DialogResult.OK)
            {
                SalienceDemo.oSalienceSession.AddSentimentDictionary(openFileDialog2.FileName, false);
            }
        }


        private void setUserDirectoryToolStripMenuItem_Click(object sender, EventArgs e)
        {
            folderBrowserDialog1.Description = "Select user directory for Salience session.";

            if (folderBrowserDialog1.ShowDialog(this) == DialogResult.OK)
            {
                SalienceDemo.oSalienceSession.SetUserDirectory(folderBrowserDialog1.SelectedPath);
                toolStripStatusLabel2.Text = "User Root: " + folderBrowserDialog1.SelectedPath;

            }
        }

        private void fixTextDisplayToolStripMenuItem_Click(object sender, EventArgs e)
        {
            bAnsiMode = !bAnsiMode;
            Encoding oTarget = bAnsiMode ? Encoding.Default : Encoding.UTF8;
            Encoding oBase = bAnsiMode ? Encoding.UTF8 : Encoding.Default;
            currentText.Text = oTarget.GetString(oBase.GetBytes(currentText.Text));
        }

        #endregion

        #region Treeview events
        //Called after something is selected in the left hand treeview
        //This is where we alter the RHS panel
        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            this.hideAllPanels();
            Point panelLocation = new Point(190, 310);
            this.CategoryIsSelected = false;
            switch (Convert.ToInt32(e.Node.Tag))
            {
                case TV_DOCUMENT_DETAILS:
                    if (this.oGetDocumentDetails == null)
                    {
                        this.oGetDocumentDetails = new ctrlGetDocumentDetails(this.currentText);
                        this.oGetDocumentDetails.Parent = this;
                        this.oGetDocumentDetails.Location = panelLocation;
                        this.oGetDocumentDetails.Visible = true;
                    }
                    else
                    {
                        this.oGetDocumentDetails.Visible = true;
                    }
                    this.oGetDocumentDetails.SetFontSize();
                    this.oGetDocumentDetails.Dock = DockStyle.Fill;
                    this.oGetDocumentDetails.BringToFront();
                    break;
                case TV_DOCUMENT_SENTIMENT:
                    if (this.oGetDocumentSentiment == null)
                    {
                        this.oGetDocumentSentiment = new ctrlGetDocumentSentiment(this.currentText);
                        this.oGetDocumentSentiment.Parent = this;
                        this.oGetDocumentSentiment.Location = panelLocation;
                        this.oGetDocumentSentiment.Visible = true;
                    }
                    else
                    {
                        this.oGetDocumentSentiment.Visible = true;
                    }
                    this.oGetDocumentSentiment.SetFontSize();
                    this.oGetDocumentSentiment.Dock = DockStyle.Fill;
                    this.oGetDocumentSentiment.BringToFront();
                    break;
                case TV_DOCUMENT_SUMMARY:
                    if (this.oGetSummary == null)
                    {
                        this.oGetSummary = new ctrlGetSummary(this.currentText);
                        this.oGetSummary.Parent = this;
                        this.oGetSummary.Location = panelLocation;
                        this.oGetSummary.Visible = true;
                    }
                    else
                    {
                        this.oGetSummary.Visible = true;
                    }
                    this.oGetSummary.SetFontSize();
                    this.oGetSummary.Dock = DockStyle.Fill;
                    this.oGetSummary.BringToFront();
                    break;
                case TV_DOCUMENT_THEMES:
                    if (this.oGetDocumentThemes == null)
                    {
                        this.oGetDocumentThemes = new ctrlGetDocumentThemes(this.currentText);
                        this.oGetDocumentThemes.Parent = this;
                        this.oGetDocumentThemes.Location = panelLocation;
                        this.oGetDocumentThemes.Visible = true;
                    }
                    else
                    {
                        this.oGetDocumentThemes.Visible = true;
                    }
                    this.oGetDocumentThemes.SetFontSize();
                    this.oGetDocumentThemes.Dock = DockStyle.Fill;
                    this.oGetDocumentThemes.BringToFront();
                    break;
                case TV_DOCUMENT_QUERY_TOPICS:
                    if (this.oGetDocumentQueryTopics == null)
                    {
                        this.oGetDocumentQueryTopics = new ctrlGetDocumentQueryTopics(this.currentText);
                        this.oGetDocumentQueryTopics.Parent = this;
                        this.oGetDocumentQueryTopics.Location = panelLocation;
                        this.oGetDocumentQueryTopics.Visible = true;
                    }
                    else
                    {
                        this.oGetDocumentQueryTopics.Visible = true;
                    }
                    this.oGetDocumentQueryTopics.SetFontSize();
                    this.oGetDocumentQueryTopics.Dock = DockStyle.Fill;
                    this.oGetDocumentQueryTopics.BringToFront();
                    break;
                case TV_DOCUMENT_CONCEPT_TOPICS:
                    if (this.oGetDocumentConceptTopics == null)
                    {
                        this.oGetDocumentConceptTopics = new ctrlGetDocumentConceptTopics(this.currentText);
                        this.oGetDocumentConceptTopics.Parent = this;
                        this.oGetDocumentConceptTopics.Location = panelLocation;
                        this.oGetDocumentConceptTopics.Visible = true;
                    }
                    else
                    {
                        this.oGetDocumentConceptTopics.Visible = true;
                    }
                    this.oGetDocumentConceptTopics.SetFontSize();
                    this.oGetDocumentConceptTopics.Dock = DockStyle.Fill;
                    this.oGetDocumentConceptTopics.BringToFront();
                    break;
                case TV_DOCUMENT_CATEGORIES:
                    if (this.oGetDocumentCategoryTopics == null)
                    {
                        this.oGetDocumentCategoryTopics = new ctrlGetDocumentCategoryTopics(this.currentText);
                        this.oGetDocumentCategoryTopics.Parent = this;
                        this.oGetDocumentCategoryTopics.Location = panelLocation;
                        this.oGetDocumentCategoryTopics.Visible = true;
                    }
                    else
                    {
                        this.oGetDocumentCategoryTopics.Visible = true;
                    }
                    this.oGetDocumentCategoryTopics.SetFontSize();
                    this.oGetDocumentCategoryTopics.Dock = DockStyle.Fill;
                    this.oGetDocumentCategoryTopics.BringToFront();
                    break;

                case TV_NAMED_ENTITY_ENTITIES:
                    if (this.oGetEntities == null)
                    {
                        this.oGetEntities = new ctrlGetEntities(this.currentText);
                        this.oGetEntities.Parent = this;
                        this.oGetEntities.Location = panelLocation;
                        this.oGetEntities.Visible = true;
                    }
                    else
                    {
                        this.oGetEntities.Visible = true;
                    }
                    this.oGetEntities.setUserEntityMode(false);
                    this.oGetEntities.SetFontSize();
                    this.oGetEntities.Dock = DockStyle.Fill;
                    this.oGetEntities.BringToFront();
                    break;
                case TV_USER_ENTITY_ENTITIES:
                    if (this.oGetUserEntities == null)
                    {
                        this.oGetUserEntities = new ctrlGetEntities(this.currentText);
                        this.oGetUserEntities.Parent = this;
                        this.oGetUserEntities.Location = panelLocation;
                        this.oGetUserEntities.Visible = true;
                    }
                    else
                    {
                        this.oGetUserEntities.Visible = true;
                    }
                    this.oGetUserEntities.setUserEntityMode(true);
                    this.oGetUserEntities.SetFontSize();
                    this.oGetUserEntities.Dock = DockStyle.Fill;
                    this.oGetUserEntities.BringToFront();
                    break;
                case TV_NAMED_ENTITY_RELATIONSHIPS:
                    if (this.oGetRelationships == null)
                    {
                        this.oGetRelationships = new ctrlGetRelationships(this.currentText);
                        this.oGetRelationships.Parent = this;
                        this.oGetRelationships.Location = panelLocation;
                        this.oGetRelationships.Visible = true;
                    }
                    else
                    {
                        this.oGetRelationships.Visible = true;
                    }
                    this.oGetRelationships.setUserEntityMode(false);
                    this.oGetRelationships.SetFontSize();
                    this.oGetRelationships.Dock = DockStyle.Fill;
                    this.oGetRelationships.BringToFront();
                    break;
                case TV_USER_ENTITY_RELATIONSHIPS:
                    if (this.oGetUserRelationships == null)
                    {
                        this.oGetUserRelationships = new ctrlGetRelationships(this.currentText);
                        this.oGetUserRelationships.Parent = this;
                        this.oGetUserRelationships.Location = panelLocation;
                        this.oGetUserRelationships.Visible = true;
                    }
                    else
                    {
                        this.oGetUserRelationships.Visible = true;
                    }
                    this.oGetUserRelationships.setUserEntityMode(true);
                    this.oGetUserRelationships.SetFontSize();
                    this.oGetUserRelationships.Dock = DockStyle.Fill;
                    this.oGetUserRelationships.BringToFront();
                    break;
                case TV_NAMED_ENTITY_OPINIONS:
                    if (this.oGetOpinions == null)
                    {
                        this.oGetOpinions = new ctrlGetOpinions(this.currentText);
                        this.oGetOpinions.Parent = this;
                        this.oGetOpinions.Location = panelLocation;
                        this.oGetOpinions.Visible = true;
                    }
                    else
                    {
                        this.oGetOpinions.Visible = true;
                    }
                    this.oGetOpinions.setUserEntityMode(false);
                    this.oGetOpinions.SetFontSize();
                    this.oGetOpinions.Dock = DockStyle.Fill;
                    this.oGetOpinions.BringToFront();
                    break;
                case TV_USER_ENTITY_OPINIONS:
                    if (this.oGetUserOpinions == null)
                    {
                        this.oGetUserOpinions = new ctrlGetOpinions(this.currentText);
                        this.oGetUserOpinions.Parent = this;
                        this.oGetUserOpinions.Location = panelLocation;
                        this.oGetUserOpinions.Visible = true;
                    }
                    else
                    {
                        this.oGetUserOpinions.Visible = true;
                    }
                    this.oGetUserOpinions.setUserEntityMode(true);
                    this.oGetUserOpinions.SetFontSize();
                    this.oGetUserOpinions.Dock = DockStyle.Fill;
                    this.oGetUserOpinions.BringToFront();
                    break;
                case TV_MARKUP_POS:
                    if (this.oGetPOSTaggedText == null)
                    {
                        this.oGetPOSTaggedText = new ctrlGetPOSTaggedText(this.currentText);
                        this.oGetPOSTaggedText.Parent = this;
                        this.oGetPOSTaggedText.Location = panelLocation;
                        this.oGetPOSTaggedText.Visible = true;
                    }
                    else
                    {
                        this.oGetPOSTaggedText.Visible = true;
                    }
                    this.oGetPOSTaggedText.Dock = DockStyle.Fill;
                    this.oGetPOSTaggedText.BringToFront();
                    break;
                case TV_MARKUP_NAMED_ENTITY:
                    if (this.oGetEntityTaggedText == null)
                    {
                        this.oGetEntityTaggedText = new ctrlGetEntityTaggedText(this.currentText);
                        this.oGetEntityTaggedText.Parent = this;
                        this.oGetEntityTaggedText.Location = panelLocation;
                        this.oGetEntityTaggedText.Visible = true;
                    }
                    else
                    {
                        this.oGetEntityTaggedText.Visible = true;
                    }
                    this.oGetEntityTaggedText.Dock = DockStyle.Fill;
                    this.oGetEntityTaggedText.BringToFront();
                    break;
                case TV_MARKUP_SENTIMENT:
                    if (this.oGetSentimentTaggedText == null)
                    {
                        this.oGetSentimentTaggedText = new ctrlGetSentimentTaggedText(this.currentText);
                        this.oGetSentimentTaggedText.Parent = this;
                        this.oGetSentimentTaggedText.Location = panelLocation;
                        this.oGetSentimentTaggedText.Visible = true;
                    }
                    else
                    {
                        this.oGetSentimentTaggedText.Visible = true;
                    }
                    this.oGetSentimentTaggedText.Dock = DockStyle.Fill;
                    this.oGetSentimentTaggedText.BringToFront();
                    break;
                case TV_MARKUP_OPINION:
                    if (this.oGetOpinionTaggedText == null)
                    {
                        this.oGetOpinionTaggedText = new ctrlGetOpinionTaggedText(this.currentText);
                        this.oGetOpinionTaggedText.Parent = this;
                        this.oGetOpinionTaggedText.Location = panelLocation;
                        this.oGetOpinionTaggedText.Visible = true;
                    }
                    else
                    {
                        this.oGetOpinionTaggedText.Visible = true;
                    }
                    this.oGetOpinionTaggedText.Dock = DockStyle.Fill;
                    this.oGetOpinionTaggedText.BringToFront();
                    break;
                case 25:
                    if (this.oGetDocumentChunks == null)
                    {
                        this.oGetDocumentChunks = new ctrlGetDocumentChunks(this.currentText);
                        this.oGetDocumentChunks.Parent = this;
                        this.oGetDocumentChunks.Location = panelLocation;
                        this.oGetDocumentChunks.Visible = true;
                    }
                    else
                    {
                        this.oGetDocumentChunks.Visible = true;
                    }
                    this.oGetDocumentChunks.Dock = DockStyle.Fill;
                    this.oGetDocumentChunks.BringToFront();
                    break;
                case 13:
                    if (this.oGetQuotes == null)
                    {
                        this.oGetQuotes = new ctrlGetEntities(this.currentText);
                        this.oGetQuotes.setQuoteMode(true);
                        this.oGetQuotes.Parent = this;
                        this.oGetQuotes.Location = panelLocation;
                        this.oGetQuotes.Visible = true;
                    }
                    else
                    {
                        this.oGetQuotes.Visible = true;
                    }
                    this.oGetQuotes.BringToFront();
                    break;
                default:
                    this.CategoryIsSelected = true;
                    break;
            }
        }

        private void treeView1_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            switch (Convert.ToInt32(e.Node.Tag))
            {
                case TV_DOCUMENT_DETAILS:
                    this.oGetDocumentDetails.processText();
                    break;
                case TV_DOCUMENT_SENTIMENT:
                    this.oGetDocumentSentiment.processText();
                    break;
                case TV_DOCUMENT_SUMMARY:
                    this.oGetSummary.processText();
                    break;
                case TV_DOCUMENT_THEMES:
                    this.oGetDocumentThemes.processText();
                    break;
                case TV_DOCUMENT_QUERY_TOPICS:
                    this.oGetDocumentQueryTopics.processText();
                    break;
                case TV_DOCUMENT_CONCEPT_TOPICS:
                    this.oGetDocumentConceptTopics.processText();
                    break;
                case TV_DOCUMENT_CATEGORIES:
                    this.oGetDocumentCategoryTopics.processText();
                    break;
                case TV_NAMED_ENTITY_ENTITIES:
                    this.oGetEntities.processText();
                    break;
                case TV_USER_ENTITY_ENTITIES:
                    this.oGetUserEntities.processText();
                    break;
                case TV_NAMED_ENTITY_RELATIONSHIPS:
                    this.oGetRelationships.processText();
                    break;
                case TV_USER_ENTITY_RELATIONSHIPS:
                    this.oGetUserRelationships.processText();
                    break;
                case TV_NAMED_ENTITY_OPINIONS:
                    this.oGetOpinions.processText();
                    break;
                case TV_USER_ENTITY_OPINIONS:
                    this.oGetUserOpinions.processText();
                    break;
                case 21:
                    this.oGetPOSTaggedText.processText();
                    break;
                case 22:
                    this.oGetEntityTaggedText.processText();
                    break;
                case 23:
                    this.oGetSentimentTaggedText.processText();
                    break;
                case 25:
                    this.oGetDocumentChunks.processText();
                    break;
                default:
                    break;
            }

        }

        #endregion

        #region Utility methods
        private void DoSplash()
        {
            splash sp = new splash();
            sp.ShowDialog();
        }

        private bool InitializeSalienceSession(bool bRestart)
        {
            bool bInitialized = false;
            try
            {
                System.Windows.Forms.Cursor.Current = Cursors.WaitCursor;
                if (bRestart && oSalienceSession != null)
                {
                    oSalienceSession.Dispose();
                }

                //Set the status strip
                toolStripStatusLabel1.Text = "";
                toolStripStatusLabel2.Text = "";

                // Look for startup options in application properties. If empty, fall back to installation defaults
                string sInstallRoot = oConfig.sInstallRoot;

                // Initialize a new session with selected data directory
                string sLicense = String.Empty;
                if (Properties.Settings.Default.LicensePath != String.Empty)
                {
                    sLicense = Properties.Settings.Default.LicensePath;
                }
                else
                {
                    sLicense = sInstallRoot + "\\license.v5";
                    Properties.Settings.Default.LicensePath = sLicense;
                    Properties.Settings.Default.Save();
                }

                SalienceStartup oStartup = new SalienceStartup();
                oStartup.sDataDirectory = oConfig.activeSettings().settings["DataDirectory"];
                oStartup.sUserDirectory = oConfig.activeSettings().settings["UserDirectory"];
                if (oConfig.activeSettings().settings["LogPath"] != String.Empty)
                {
                    if (Boolean.Parse(oConfig.activeSettings().settings["LogStartup"]))
                        oStartup.sLogPath = oConfig.activeSettings().settings["LogPath"];
                }
                else
                {
                    oStartup.sLogPath = String.Empty;
                }

                switch (oConfig.activeSettings().settings["Name"])
                {
                    case "twitter_data":
                        oStartup.nMode = SALIENCE_MODE.SHORTFORM;
                        break;
                    default:
                        oStartup.nMode = SALIENCE_MODE.DEFAULT;
                        break;
                }
                cmbModeSwitch.SelectedIndex = Properties.Settings.Default.nMode;

                SalienceDemo.oSalienceSession = new SalienceFive(sLicense, oStartup);

                oConfig.changedOptions.Clear();
                oConfig.changedOptions = new SortedList<string, string>(oConfig.activeSettings().settings);
                bInitialized = this.SetSalienceOptions();

                //Set the status strip
                toolStripStatusLabel1.Text = "Data Root: " + oStartup.sDataDirectory;
                toolStripStatusLabel2.Text = "User Root: " + oStartup.sUserDirectory;

                
            }
            catch (SalienceException errSalience)
            {
                System.Windows.Forms.Cursor.Current = Cursors.Default;
                MessageBox.Show("Salience session initialization failed. \n" + errSalience.Message, "Salience Demo", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
            catch (Exception err)
            {
                System.Windows.Forms.Cursor.Current = Cursors.Default;
                MessageBox.Show(err.Message, "Salience Demo", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }

            return bInitialized;
        }

        private bool SetSalienceOptions()
        {
            bool bConfigured = false;
            List<string> errorList = new List<string>();


            /** BASE OPTIONS **/
            try
            {
                if (oConfig.changedOptions.ContainsKey("TextThreshold"))
                    SalienceDemo.oSalienceSession.TextThreshold = Convert.ToInt32(oConfig.activeSettings().settings["TextThreshold"]);
            }
            catch { errorList.Add("Text Threshold"); }
            try
            {
                if (oConfig.changedOptions.ContainsKey("ListsandTables"))
                    SalienceDemo.oSalienceSession.CalculateListsAndTables = Boolean.Parse(oConfig.activeSettings().settings["ListsandTables"]);
            }
            catch { errorList.Add("Lists and Tables"); }
            try
            {
                if (oConfig.changedOptions.ContainsKey("TextTimeout"))
                    SalienceDemo.oSalienceSession.ExecutionTimeout = Convert.ToInt32(oConfig.activeSettings().settings["TextTimeout"]);
            }
            catch { errorList.Add("Max Execution Time"); }
            try
            {
                bool dude = Boolean.Parse(oConfig.activeSettings().settings["FailLongSentences"]);
                if (oConfig.changedOptions.ContainsKey("FailLongSentences"))
                    SalienceDemo.oSalienceSession.FailOnLongSentences = Boolean.Parse(oConfig.activeSettings().settings["FailLongSentences"]);
            }
            catch { errorList.Add("Fail on Long Sentences"); }
            try
            {
                if (oConfig.changedOptions.ContainsKey("ConceptSlop"))
                {
                    double cSlop = Convert.ToDouble(oConfig.activeSettings().settings["ConceptSlop"]);
                    SalienceDemo.oSalienceSession.ConceptSlop = (float)cSlop;
                }
            }
            catch { errorList.Add("Concept Slop"); }
            try
            {
                if (oConfig.changedOptions.ContainsKey("DocumentSemantics"))
                    SalienceDemo.oSalienceSession.UseSemantics = Boolean.Parse(oConfig.activeSettings().settings["DocumentSemantics"]);
            }
            catch { errorList.Add("Document Semantics"); }
            try
            {
                if (oConfig.changedOptions.ContainsKey("UserDirectory"))
                {
                    if (String.IsNullOrEmpty(oConfig.activeSettings().settings["UserDirectory"]))
                    {
                        oConfig.activeSettings().settings["UserDirectory"] = oConfig.activeSettings().settings["DataDirectory"] + "\\user";
                        oConfig.activeSettings().Save();
                    }
                    SalienceDemo.oSalienceSession.UserDirectory = oConfig.activeSettings().settings["UserDirectory"];
                }
            }
            catch { errorList.Add("User Directory"); }
            try
            {
                if (oConfig.changedOptions.ContainsKey("OneSentence"))
                    SalienceDemo.oSalienceSession.ProcessAsOneSentence = Boolean.Parse(oConfig.activeSettings().settings["OneSentence"]);
            }
            catch { errorList.Add("Process as One Sentence"); }
            try
            {
                if (oConfig.changedOptions.ContainsKey("SharedMemory"))
                    SalienceDemo.oSalienceSession.UseSharedMemory = Boolean.Parse(oConfig.activeSettings().settings["SharedMemory"]);
            }
            catch { errorList.Add("Shared Memory"); }
            try
            {
                if (oConfig.changedOptions.ContainsKey("ComplexStems"))
                    SalienceDemo.oSalienceSession.ProcessComplexStems = Boolean.Parse(oConfig.activeSettings().settings["ComplexStems"]);
            }
            catch { errorList.Add("Complex Stems"); }
            try
            {
                if (oConfig.changedOptions.ContainsKey("FlattenAllUppercase"))
                    SalienceDemo.oSalienceSession.FlattenAllUpperCase = Boolean.Parse(oConfig.activeSettings().settings["FlattenAllUppercase"]);
            }
            catch { errorList.Add("Flatten All Uppercase"); }

            /** CONCEPT TOPIC OPTIONS **/

            try
            {
                if (oConfig.changedOptions.ContainsKey("MaxConceptHits"))
                    SalienceDemo.oSalienceSession.MaxConceptHits = Convert.ToInt32(oConfig.activeSettings().settings["MaxConceptHits"]);
            }
            catch { errorList.Add("Max Concept Hits"); }
            try
            {
                if (oConfig.changedOptions.ContainsKey("MinConceptScore"))
                {
                    double cWindowSize = Convert.ToDouble(oConfig.activeSettings().settings["MinConceptScore"]);
                    SalienceDemo.oSalienceSession.MinConceptScore = (float)cWindowSize;
                }
            }
            catch { errorList.Add("Min Concept Score"); }
            try
            {
                if (oConfig.changedOptions.ContainsKey("ConceptTopicWindowSize"))
                    SalienceDemo.oSalienceSession.ConceptWindowSize = Convert.ToInt32(oConfig.activeSettings().settings["ConceptTopicWindowSize"]);
            }
            catch { errorList.Add("Concept Topic Window Size"); }
            try
            {
                if (oConfig.changedOptions.ContainsKey("ConceptTopicWindowJump"))
                    SalienceDemo.oSalienceSession.ConceptTopicJump = Convert.ToInt32(oConfig.activeSettings().settings["ConceptTopicWindowJump"]);
            }
            catch { errorList.Add("Concept Topic Window Jump"); }
            try
            {
                if (oConfig.changedOptions.ContainsKey("NongrammaticalTopics"))
                    SalienceDemo.oSalienceSession.NongrammaticalTopics = Boolean.Parse(oConfig.activeSettings().settings["NongrammaticalTopics"]);
            }
            catch { errorList.Add("Nongrammatical Topics"); }

            try
            {
                // Set the default concept topic file if does not exist
                if (oConfig.changedOptions.ContainsKey("DefaultConceptTopicFile"))
                {
                    if (String.IsNullOrEmpty(oConfig.activeSettings().settings["DefaultConceptTopicFile"]))
                    {
                        oConfig.activeSettings().settings["DefaultConceptTopicFile"] = oConfig.activeSettings().settings["DataDirectory"] + "\\salience\\concepts\\example.dat";
                        oConfig.activeSettings().Save();
                    }
                    SalienceDemo.oSalienceSession.ConceptTopics = oConfig.activeSettings().settings["DefaultConceptTopicFile"];
                }
            }
            catch { errorList.Add("Concept Topic List"); }

            /** ENTITY OPTIONS **/

            try
            {
                if (oConfig.changedOptions.ContainsKey("RequiredEntities"))
                    if (oConfig.activeSettings().settings["RequiredEntities"] == null)
                    {
                        oConfig.activeSettings().settings["RequiredEntities"] = "";
                    }
                SalienceDemo.oSalienceSession.RequiredEntities = oConfig.activeSettings().settings["RequiredEntities"];
            }
            catch { errorList.Add("Required Entities"); }
            try
            {
                if (oConfig.changedOptions.ContainsKey("AnaphoraResolution"))
                    SalienceDemo.oSalienceSession.AnaphoraResolution = Boolean.Parse(oConfig.activeSettings().settings["AnaphoraResolution"]);
            }
            catch { errorList.Add("Anaphora Resolution"); }
            try
            {
                if (oConfig.changedOptions.ContainsKey("ModelSensitivity"))
                {
                    double mSensitivity = Convert.ToDouble(oConfig.activeSettings().settings["ModelSensitivity"]);
                    SalienceDemo.oSalienceSession.ModelSensitivity = (float)mSensitivity;
                }
            }
            catch { errorList.Add("Model Sensitivity"); }
            try
            {
                if (oConfig.changedOptions.ContainsKey("EntityThreshold"))
                    SalienceDemo.oSalienceSession.EntityThreshold = Convert.ToInt32(oConfig.activeSettings().settings["EntityThreshold"]);
            }
            catch { errorList.Add("Entity Threshold"); }
            try
            {
                if (oConfig.changedOptions.ContainsKey("EntitySummaryLength"))
                    SalienceDemo.oSalienceSession.EntitySummaryLength = Convert.ToInt32(oConfig.activeSettings().settings["EntitySummaryLength"]);
            }
            catch { errorList.Add("Entity Summary Length"); }
            try
            {
                if (oConfig.changedOptions.ContainsKey("EntityOverlap"))
                    SalienceDemo.oSalienceSession.EntityOverlap = Boolean.Parse(oConfig.activeSettings().settings["EntityOverlap"]);
            }
            catch { errorList.Add("Entity Overlap"); }
            try
            {
                if (oConfig.changedOptions.ContainsKey("UserEntityList"))
                    SalienceDemo.oSalienceSession.EntityList = oConfig.activeSettings().settings["UserEntityList"];
            }
            catch { errorList.Add("User Entity List"); }
            try
            {
                if (oConfig.changedOptions.ContainsKey("OverlapSentimentThemes"))
                    SalienceDemo.oSalienceSession.SentimentThemeOverlap = Boolean.Parse(oConfig.activeSettings().settings["OverlapSentimentThemes"]);
            }
            catch { errorList.Add("Overlap Sentiment Themes"); }
            try
            {
                if (oConfig.changedOptions.ContainsKey("EntityTopics"))
                    SalienceDemo.oSalienceSession.EntityTopics = Boolean.Parse(oConfig.activeSettings().settings["EntityTopics"]);
            }
            catch { errorList.Add("Entity Topics"); }

            /** SENTIMENT OPTIONS **/
            try
            {
                if (oConfig.changedOptions.ContainsKey("DefaultHSDFile"))
                {
                    if (String.IsNullOrEmpty(oConfig.activeSettings().settings["DefaultHSDFile"]))
                    {
                        if (File.Exists(oConfig.activeSettings().settings["DataDirectory"] + "\\salience\\sentiment\\general.hsdx"))
                            oConfig.activeSettings().settings["DefaultHSDFile"] = oConfig.activeSettings().settings["DataDirectory"] + "\\salience\\sentiment\\general.hsdx";
                        else
                            oConfig.activeSettings().settings["DefaultHSDFile"] = oConfig.activeSettings().settings["DataDirectory"] + "\\salience\\sentiment\\general.hsd";
                        oConfig.activeSettings().Save();
                    }
                    string[] arrSentimentFiles = oConfig.activeSettings().settings["DefaultHSDFile"].ToString().Split(';');
                    for (int i = arrSentimentFiles.GetUpperBound(0); i >= 0; i--)
                    {
                        if (i == arrSentimentFiles.GetUpperBound(0))
                            SalienceDemo.oSalienceSession.AddSentimentDictionary(arrSentimentFiles[i], true);
                        else
                            SalienceDemo.oSalienceSession.AddSentimentDictionary(arrSentimentFiles[i], false);
                    }
                    
                }
            }
            catch { errorList.Add("Set Sentiment Dictionary"); }
            try
            {
                if (oConfig.changedOptions.ContainsKey("AddSentimentDictionary"))
                    SalienceDemo.oSalienceSession.AddSentimentDictionary(oConfig.activeSettings().settings["AddSentimentDictionary"], false);
            }
            catch { errorList.Add("Add Sentiment Dictionary"); }
            try
            {
                if (oConfig.changedOptions.ContainsKey("UsePolarityModel"))
                    SalienceDemo.oSalienceSession.UsePolarityModel = Boolean.Parse(oConfig.activeSettings().settings["UsePolarityModel"]);
            }
            catch { errorList.Add("Use Polarity Model"); }
            try
            {
                if (oConfig.changedOptions.ContainsKey("ReturnAllPossibleSentiment"))
                    SalienceDemo.oSalienceSession.SetAllSentimentPhrases = Boolean.Parse(oConfig.activeSettings().settings["ReturnAllPossibleSentiment"]);
            }
            catch { errorList.Add("Show All Possible Phrases"); }
            try
            {
                if (oConfig.changedOptions.ContainsKey("EmphaticMultiplier"))
                {
                    double cEmphaticMultiplier = Convert.ToDouble(oConfig.activeSettings().settings["EmphaticMultiplier"]);
                    SalienceDemo.oSalienceSession.EmphaticModifier = (float)cEmphaticMultiplier;
                }
            }
            catch { errorList.Add("Emphatic Multiplier"); }
            try
            {
                if (oConfig.changedOptions.ContainsKey("SuperlativeMultiplier"))
                {
                    double cSuperlativeMultiplier = Convert.ToDouble(oConfig.activeSettings().settings["SuperlativeMultiplier"]);
                    SalienceDemo.oSalienceSession.SuperlativeModifier = (float)cSuperlativeMultiplier;
                }
            }
            catch { errorList.Add("Superlative Multiplier"); }

            /** QUERY TOPIC OPTIONS **/
            try
            {
                if (oConfig.changedOptions.ContainsKey("TopicStemming"))
                    SalienceDemo.oSalienceSession.TopicStemming = Boolean.Parse(oConfig.activeSettings().settings["TopicStemming"]);
            }
            catch { errorList.Add("Topic Stemming"); }
            try
            {
                // Set the default query topic file if it does not exist
                if (oConfig.changedOptions.ContainsKey("DefaultQueryTopicFile"))
                {
                    if (String.IsNullOrEmpty(oConfig.activeSettings().settings["DefaultQueryTopicFile"]))
                    {
                        oConfig.activeSettings().settings["DefaultQueryTopicFile"] = oConfig.activeSettings().settings["DataDirectory"] + "\\salience\\tags\\sampletags.dat";
                        oConfig.activeSettings().Save();
                    }
                    SalienceDemo.oSalienceSession.TopicList = oConfig.activeSettings().settings["DefaultQueryTopicFile"];
                }
            }
            catch { errorList.Add("Query Topic List"); }

            /** THEME OPTIONS **/
            try
            {
                if (oConfig.changedOptions.ContainsKey("ThemeTopics"))
                    SalienceDemo.oSalienceSession.ThemeTopics = Boolean.Parse(oConfig.activeSettings().settings["ThemeTopics"]);
            }
            catch { errorList.Add("Theme Topics"); }
            try
            {
                if (oConfig.changedOptions.ContainsKey("ExplainCategories"))
                    SalienceDemo.oSalienceSession.ExplainCategories = Boolean.Parse(oConfig.activeSettings().settings["ExplainCategories"]);
            }
            catch { errorList.Add("Explain Categories"); }
            try
            {
                if (oConfig.changedOptions.ContainsKey("HTMLContent"))
                    SalienceDemo.oSalienceSession.ContentHTML = Boolean.Parse(oConfig.activeSettings().settings["HTMLContent"]);
            }
            catch { errorList.Add("HTML Content"); }
            
            if (errorList.Count > 0)
            {
                RevertOptions();
                string errorText = "Error configuring Salience session options. Your options have been reverted back to the previous values. The following options caused the error:\n";
                foreach (string error in errorList)
                {
                    errorText += "\t";
                    errorText += error;
                    errorText += "\n";
                }
                MessageBox.Show(errorText, "Salience Demo", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                bConfigured = true;
            }
            else
                bConfigured = true;

            return bConfigured;
        }

        private void RevertOptions()
        {
            foreach (KeyValuePair<string, string> key in oConfig.changedOptions)
            {
                oConfig.activeSettings().settings[key.Key.ToString()] = key.Value.ToString();
            }
            oConfig.activeSettings().Save();
            oConfig.activeSettings().Save();
        }

        /// <summary>
        /// Helper method to enable or disable the user interface depending on status of Salience session. We want to avoid UI being used if Salience
        /// session has not initialized properly, because user may not be aware that subsequent operations with analyzing text would fail.
        /// </summary>
        /// <param name="bEnable">Flag to enable or disable the UI</param>
        private void EnableUI(bool bEnable)
        {
            loadFileToolStripMenuItem.Enabled = bEnable;
            treeView1.Enabled = bEnable;
            m_bUIEnabled = bEnable;
        }

        private void hideAllPanels()
        {
            if (this.oGetEntities != null) {this.oGetEntities.Visible = false;}
            if (this.oGetUserEntities != null) {this.oGetUserEntities.Visible = false;}
            if (this.oGetSimpleEntities != null) {this.oGetSimpleEntities.Visible = false;}
            if (this.oGetQuotes != null) {this.oGetQuotes.Visible = false;}
            if (this.oGetPOSTaggedText != null) {this.oGetPOSTaggedText.Visible = false;}
            if (this.oGetEntityTaggedText != null) {this.oGetEntityTaggedText.Visible = false;}
            if (this.oGetSummary != null) {this.oGetSummary.Visible = false;}
            if (this.oGetOpinionTaggedText != null) {this.oGetOpinionTaggedText.Visible = false;}
            if (this.oGetSentimentTaggedText != null) {this.oGetSentimentTaggedText.Visible = false;}
            if (this.oGetDocumentSentiment != null) {this.oGetDocumentSentiment.Visible = false;}
            if (this.oGetDocumentThemes != null) {this.oGetDocumentThemes.Visible = false;}
            if (this.oGetDocumentChunks != null) {this.oGetDocumentChunks.Visible = false;}
            if (this.oGetRelationships != null) {this.oGetRelationships.Visible = false;}
            if (this.oGetUserRelationships != null) { this.oGetUserRelationships.Visible = false; }
            if (this.oGetOpinions != null) { this.oGetOpinions.Visible = false; }
            if (this.oGetUserOpinions != null) {this.oGetUserOpinions.Visible = false;}
            if (this.oGetDocumentDetails != null) {this.oGetDocumentDetails.Visible = false;}
            if (this.oGetDocumentQueryTopics != null) {this.oGetDocumentQueryTopics.Visible = false;}
            if (this.oGetDocumentConceptTopics != null) {this.oGetDocumentConceptTopics.Visible = false;}
            if (this.oGetDocumentCategoryTopics != null) { this.oGetDocumentCategoryTopics.Visible = false; }

        }

        public string getCurrentText()
        {
            return currentText.Text;
        }
        #endregion

        private void SalienceDemo_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (m_bUIEnabled)
                oSalienceSession.Dispose();
        }

        private void SalienceDemo_Load(object sender, EventArgs e)
        {
            // This will trigger a SelectedIndexChanged event, which will initialize the session
            cmbModeSwitch.SelectedIndex = Properties.Settings.Default.nMode;
            // Hack to prevent invalid UI state from failure to set options on load
            if (m_bUIEnabled)
                SetSalienceOptions();
        }

        private void cmbModeSwitch_SelectedIndexChanged(object sender, EventArgs e)
        {
            bool bProfileChanged = false;

            if (cmbModeSwitch.SelectedIndex != Properties.Settings.Default.nMode)
            {
                if (cmbModeSwitch.SelectedIndex == cmbModeSwitch.Items.Count - 1)
                {
                    Dialogs.CustomProfileDialog AddNewCustomProfile = new Dialogs.CustomProfileDialog(this);
                    if (AddNewCustomProfile.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                        bProfileChanged = true;
                    else
                        cmbModeSwitch.SelectedIndex = Properties.Settings.Default.nMode;
                }
                else
                {
                    Properties.Settings.Default.nMode = cmbModeSwitch.SelectedIndex;
                    Properties.Settings.Default.Save();
                    bProfileChanged = true;
                }
            }
            else
            {
                if (oSalienceSession == null)
                    bProfileChanged = true;
            }

            // Only reinitialize the session if the profile actually changed (or if new profile was actually created)
            if (bProfileChanged)
            {
                if (!InitializeSalienceSession(true))
                    EnableUI(false);
                else
                    EnableUI(true);
            }
        }

        private void SalienceDemo_Resize(object sender, EventArgs e)
        {
            // Document level function controls
            if (this.oGetDocumentDetails != null) { this.oGetDocumentDetails.Dock = DockStyle.Fill; }
            if (this.oGetSummary != null) { this.oGetSummary.Dock = DockStyle.Fill; }
            if (this.oGetDocumentSentiment != null) { this.oGetDocumentSentiment.Dock = DockStyle.Fill; }
            if (this.oGetDocumentThemes != null) { this.oGetDocumentThemes.Dock = DockStyle.Fill; }
            if (this.oGetDocumentQueryTopics != null) { this.oGetDocumentQueryTopics.Dock = DockStyle.Fill; }
            if (this.oGetDocumentConceptTopics != null) { this.oGetDocumentConceptTopics.Dock = DockStyle.Fill; }
            if (this.oGetDocumentCategoryTopics != null) { this.oGetDocumentCategoryTopics.Dock = DockStyle.Fill; }

            // Entity level function controls
            if (this.oGetEntities != null) { this.oGetEntities.Dock = DockStyle.Fill; }
            if (this.oGetRelationships != null) { this.oGetRelationships.Dock = DockStyle.Fill; }
            if (this.oGetOpinions != null) { this.oGetOpinions.Dock = DockStyle.Fill; }

            if (this.oGetUserEntities != null) { this.oGetUserEntities.Dock = DockStyle.Fill; }
            if (this.oGetUserRelationships != null) { this.oGetUserRelationships.Dock = DockStyle.Fill; }
            if (this.oGetUserOpinions != null) { this.oGetUserOpinions.Dock = DockStyle.Fill; }

            // Marked up text function controls
            if (this.oGetPOSTaggedText != null) { this.oGetPOSTaggedText.Dock = DockStyle.Fill; }
            if (this.oGetEntityTaggedText != null) { this.oGetEntityTaggedText.Dock = DockStyle.Fill; }
            if (this.oGetOpinionTaggedText != null) { this.oGetOpinionTaggedText.Dock = DockStyle.Fill; }
            if (this.oGetSentimentTaggedText != null) { this.oGetSentimentTaggedText.Dock = DockStyle.Fill; }
            if (this.oGetDocumentChunks != null) { this.oGetDocumentChunks.Dock = DockStyle.Fill; }
        }

        private void currentText_TextChanged(object sender, EventArgs e)
        {
            // If we have no text, then the Process button on the current result panel (or in reality, any of them) should be disabled.
            if (this.oGetEntities != null) { this.oGetEntities.EnableProcessButton(); }
            if (this.oGetUserEntities != null) { this.oGetUserEntities.EnableProcessButton(); }
            if (this.oGetSimpleEntities != null) { this.oGetSimpleEntities.EnableProcessButton(); }
            if (this.oGetQuotes != null) { this.oGetQuotes.EnableProcessButton(); }
            if (this.oGetPOSTaggedText != null) { this.oGetPOSTaggedText.EnableProcessButton(); }
            if (this.oGetEntityTaggedText != null) { this.oGetEntityTaggedText.EnableProcessButton(); }
            if (this.oGetSummary != null) { this.oGetSummary.EnableProcessButton(); }
            if (this.oGetOpinionTaggedText != null) { this.oGetOpinionTaggedText.EnableProcessButton(); }
            if (this.oGetSentimentTaggedText != null) { this.oGetSentimentTaggedText.EnableProcessButton(); }
            if (this.oGetDocumentSentiment != null) { this.oGetDocumentSentiment.EnableProcessButton(); }
            if (this.oGetDocumentThemes != null) { this.oGetDocumentThemes.EnableProcessButton(); }
            if (this.oGetDocumentChunks != null) { this.oGetDocumentChunks.EnableProcessButton(); }
            if (this.oGetRelationships != null) { this.oGetRelationships.EnableProcessButton(); }
            if (this.oGetUserRelationships != null) { this.oGetUserRelationships.EnableProcessButton(); }
            if (this.oGetOpinions != null) { this.oGetOpinions.EnableProcessButton(); }
            if (this.oGetUserOpinions != null) { this.oGetUserOpinions.EnableProcessButton(); }
            if (this.oGetDocumentDetails != null) { this.oGetDocumentDetails.EnableProcessButton(); }
            if (this.oGetDocumentQueryTopics != null) { this.oGetDocumentQueryTopics.EnableProcessButton(); }
            if (this.oGetDocumentConceptTopics != null) { this.oGetDocumentConceptTopics.EnableProcessButton(); }
            if (this.oGetDocumentCategoryTopics != null) { this.oGetDocumentCategoryTopics.EnableProcessButton(); }
        }
    }
}

